﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using fbasync.webcomponents;
using fbasync.Exceptions;

namespace fbasync.web
{
    public partial class Stream : FacebookPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
        }

        protected string ApiKey { get { return Connection.ApplicationKey; } }

        protected void OnPublish(object sender, EventArgs e)
        {
            uiViews.Visible = true;
            try
            {
                var attach = new Attachment
                {
                    caption = "Caption for attachment",
                    description = "Description for attachment",
                    href = "http://www.joemagner.com",
                    name = "Hopefully this works",
                    media = new List<AttachmentMedia>
                    {
                        new AttachmentMediaImage
                        {
                            href = "http://icanhascheezburger.com/2009/03/30/funny-pictures-awlll-gone-cookie-now/",
                            src = "http://icanhascheezburger.files.wordpress.com/2009/03/funny-pictures-kitten-finished-his-milk-and-wants-a-cookie.jpg",
                        },
                    },
                    properties = new AttachmentProperty
                    {
                        category = new ActionLink
                        {
                            href = "#",
                            text = "Sample",
                        },
                        ratings = "5 stars",
                    },
                };

                var action_links = new List<ActionLink> {
                    new ActionLink {
                        href = "http://www.genuineinteractive.com/",
                        text = "Genuine Interactive",
                    },
                };

                var ar = Connection.BeginPublishToStream(
                    uiMessage.Text.Trim(),
                    attach,
                    action_links,
                    0, 0, null, null);
                long id = Connection.EndPublishToStream(ar);
                uiViews.ActiveViewIndex = 0;
                uiResult.Text = id.ToString();
            }
            catch (AsynchronousException ex)
            {
                if (ex.InnerException is FacebookPermissionException)
                {
                    uiViews.ActiveViewIndex = 1;
                    uiAddPermissionLink.NavigateUrl = string.Format(uiAddPermissionLink.NavigateUrl, Connection.ApplicationKey, Server.UrlEncode("http://apps.facebook.com/fbasync/stream.aspx"));
                }
                else
                {
                    throw;
                }
            }
        }
    }
}
